package acom.dhy.qigsaw2test

import android.app.Application
import android.content.Context
import android.content.res.Resources
import androidx.multidex.MultiDex
import com.dhy.qigsaw.splash.SampleAppKiller
import com.dhy.qigsaw.splash.data.SplitInfoUpdated
import com.dhy.qigsaw.splash.data.TestCase
import com.dhy.qigsaw.splash.updateQigsawConfigDynamicFeatures
import com.dhy.qigsawsplitdownloader.SimpleDownloader
import com.dhy.qigsawsplitdownloader.SplitCacheUtil
import com.donald.dps.lib.DynamicProviderSwitch
import com.iqiyi.android.qigsaw.core.Qigsaw
import com.iqiyi.android.qigsaw.core.SplitConfiguration
import com.iqiyi.android.qigsaw.core.splitload.SplitLoad
import com.tencent.bugly.crashreport.CrashReport
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class App : Application() {
    companion object {
        @JvmStatic
        val testCases: MutableMap<TestCase, Boolean> = mutableMapOf()

        @JvmField
        var AUTO_TEST_MODE = BuildConfig.AUTO_TEST_MODE
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
        initDynamicProviderSwitch()
    }

    private fun initQigsaw() {
        updateQigsawConfigDynamicFeatures()
        SplitCacheUtil.initOkDownload(this)

        val configuration = SplitConfiguration.newBuilder()
            .splitLoadMode(SplitLoad.SINGLE_CLASSLOADER)
            .verifySignature(false)
            .build()
        Qigsaw.install(this, SimpleDownloader(this, threshold = Long.MAX_VALUE, log = true), configuration)
    }

    override fun onCreate() {
        super.onCreate()
        initAppKiller()
        initQigsaw()
        CrashReport.initCrashReport(this, BuildConfig.BUGLY_APPID, BuildConfig.DEBUG)
        Qigsaw.onApplicationCreated()
        Qigsaw.preloadInstalledSplits(null)
    }

    private fun initAppKiller() {
        SampleAppKiller.init(this)
        EventBus.getDefault().register(this)
    }

    @Subscribe
    fun onSplitInfoUpdated(info: SplitInfoUpdated) {
        EventBus.getDefault().removeStickyEvent(info)
        SampleAppKiller.start()
    }

    private var providerSwitch: DynamicProviderSwitch? = null

    /**
     * call after MultiDex.install, before initQigsaw
     * */
    private fun initDynamicProviderSwitch() {
        providerSwitch = DynamicProviderSwitch(this, true)
    }

    override fun getResources(): Resources {
        val res = super.getResources()
        Qigsaw.onApplicationGetResources(res)

        if (providerSwitch != null) {
            providerSwitch!!.startDynamicProviders()
            if (providerSwitch!!.isFinish()) providerSwitch = null
        }
        return res
    }
}